﻿using Newtonsoft.Json;

namespace Singer.Core;

/// <summary>
/// Json工具类
/// </summary>
public static class JsonUtils
{
    public static T? ToModel<T>(this string json)
    {
        return JsonConvert.DeserializeObject<T>(json);
    }

    public static object? ToModel(this string json, Type type)
    {
        return JsonConvert.DeserializeObject(json, type);
    }
    
    /// <summary>
    /// 对象转json字符串
    /// </summary>
    /// <param name="obj"></param>
    /// <param name="indented">是否带缩进符，保留json格式</param>
    public static string ToJson(this object obj, bool indented = false)
    {
        JsonSerializerSettings settings = new JsonSerializerSettings
        {
            DateFormatString = "yyyy-MM-dd HH:mm:ss",
            NullValueHandling = NullValueHandling.Include
        };
        return JsonConvert.SerializeObject(obj, indented ? Formatting.Indented : Formatting.None, settings);
    }
}
